package edu.gatech.cs2340.teamrocket.control.networking.dialog;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import edu.gatech.cs2340.teamrocket.control.networking.message.Message;

/**
 * Sends Message objects over the Socket.
 *
 * @author Joe Tacheron
 */
public class MessageSender implements Runnable {

    private Dialog dialog;
    private ObjectOutputStream out;
    private Queue<Message> sendQueue;
    private volatile boolean quit;

    public MessageSender(Dialog dialog, Socket socket) throws IOException {
        this.dialog = dialog;
        this.out = new ObjectOutputStream(socket.getOutputStream());
        this.sendQueue = new LinkedBlockingQueue<Message>();
    }

    /**
     * Waits for objects to be given in order to send.
     */
    @Override
    public synchronized void run(){
        while(!quit || !sendQueue.isEmpty()){
            if(sendQueue.isEmpty()){
                try {
                    wait();
                }
                catch (InterruptedException ignore) { }
            }
            else{
                try {
                    out.writeObject(sendQueue.poll());
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Send a new Message.
     *
     * @param m
     */
    public synchronized void sendMessage(Message m){
        sendQueue.add(m);
        notify();
    }

    /**
     * End this thread.
     */
    public synchronized void close(){
        quit = true;
        notify();
    }
}
